<?php
class Mygzip{
    protected $expire = "3600 * 24 * 30";
    protected $path = '';

    public function __construct($set_expire='',$set_path=''){
	if(intval($set_expire) > 0){
            $this->expire = $set_expire;
        }
        if($set_path){
            $this->path = $set_path;
        }
    }

    public function __destruct(){

    }

    public function check_mod(){
        if(extension_loaded('zlib') && strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")){
            return true;
        }else{
            return false;
        }
    }

    public function create_gzip($from_file,$to_file,$type='js'){
        if(!$this->check_mod())
            die("没有gzip模块");
        if(!is_array($from_file))
            die("参数必须为数组");
        switch ($type){
            case "js":
                header("Content-type: text/javascript");
            break;
            case "css":
                header("Content-type: text/css");
            break;
            default:
            break;

        }
        header("Vary: Accept-Encoding");
        header("Expires: " . gmdate("D, d M Y H:i:s", time() + $this->expire)." GMT");
        foreach ($from_file as $data){
            $content .=file_get_contents($data);
        }
        $content = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $content);         //去注释
        $cache = gzencode($content, 6, FORCE_GZIP);
        $rs = file_put_contents($this->path.$to_file, $cache);
        return $rs;                                                     //输出字节长度
    }

    public function get_gzip($file){
        $file = $this->path.$file;
        if(is_file($file)){
            header("Content-Encoding: identity");
            $html = '<script type="text/javascript">';
            $html.= $this->my_gzdecode(file_get_contents($file));
            $html .= '</script>';
            return $html;
        }
    }
    
    public function my_gzdecode($data){
        if($data){
            if (function_exists('gzdecode')) {
                return gzdecode($data);
            }else{
                $flags = ord(substr($data, 3, 1));
                $headerlen = 10;
                $extralen = 0;
                $filenamelen = 0;
                if ($flags & 4) {
                    $extralen = unpack('v' ,substr($data, 10, 2));
                    $extralen = $extralen[1];
                    $headerlen += 2 + $extralen;
                }
                if ($flags & 8) // Filename
                    $headerlen = strpos($data, chr(0), $headerlen) + 1;
                if ($flags & 16) // Comment
                    $headerlen = strpos($data, chr(0), $headerlen) + 1;
                if ($flags & 2) // CRC at end of file
                    $headerlen += 2;
                $unpacked = @gzinflate(substr($data, $headerlen));
                if ($unpacked === FALSE)
                    $unpacked = $data;
                return $unpacked;
            }
        }else {
            die('没有加密的数据');
        }
    }
}
?>
